<?php
/**
 * Created by PhpStorm.
 * User: Neho
 * Date: 2017/11/12
 * Time: 12:41
 */

namespace app\common\service;

use think\Model;
use think\Config;

class Wx extends Model
{
    public function authDomain()
    {
        $wx = &load_wechat('Receive');
        /* 验证接口 */
        if ($wx->valid() === FALSE) {
            // 接口验证错误，记录错误日志
            // log_message('ERROR', "微信被动接口验证失败，{$wechat->errMsg}[{$wechat->errCode}]");
            // 退出程序
            exit($wx->errMsg);
        }
    }

    //js签名
    public function getJsSign($url)
    {
        // 创建SDK实例
        $script = &load_wechat('Script');

        // 获取JsApi使用签名，通常这里只需要传 $ur l参数
        $options = $script->getJsSign($url);

        // 处理执行结果
        if ($options === FALSE) {
            // 接口失败的处理
            echo $script->errMsg;
        } else {
            // 接口成功的处理
            return $options;
        }
    }

    //获取微信用户信息
    public function getUserInfo($access_token, $openid)
    {
        $url = "https://api.weixin.qq.com/sns/userinfo";
        $params = [
            "access_token" => $access_token,
            "openid" => $openid,
            "lang" => "zh_CN"
        ];
        $userInfo = &http($url, $params);
        return $userInfo;
    }

    //获取用户信息凭证access_token
    public function getUserAccessToken($code)
    {
        $config = Config::get('Wx');
        $url = "https://api.weixin.qq.com/sns/oauth2/access_token";
        $params = [
            "appid" => $config["appid"],
            "secret" => $config["appsecret"],
            "code" => $code,
            "grant_type" => "authorization_code"
        ];
        $userAccessToken = &http($url, $params);
        return $userAccessToken;
    }

    //刷新用户凭证access_token
    public function refreshUserAccessToken()
    {
        $config = Config::get('Wx');
        $url = "https://api.weixin.qq.com/sns/oauth2/access_token";
        $params = [
            "appid" => $config["appid"],
            "refresh_token" => $config["secret"],
            "grant_type" => "refresh_token"
        ];
        $userAccessToken = &http($url, $params);
        return $userAccessToken;
    }
}